<template>
  <div class="pdf-viewer">
    <div class="top-operate-area" v-if="processStatus < 6">
      <div class="sigle-translate">
        <div ref="translating" class="translating"></div>
        <div>数字材料助理工程师正在为解析全文中....</div>
      </div>
    </div>
    <template v-else>
      <div class="top-operate-area" v-if="languageCode !== LANGUAGE_CODE.中文">
        <div v-show="tranStatus === -1 && processStatus >= 6" class="sigle-translate" @click="startTranslate(0)">
          <img src="@/static/image/documentUpload/translate-icon1.png" />
          <div>全文翻译</div>
        </div>
        <div v-show="tranStatus === 0" class="sigle-translate">
          <div ref="translating" class="translating"></div>
          <div>数字材料助理工程师正在为您翻译全文中....</div>
        </div>
        <div v-show="tranStatus === 1 && !pdfLoading" class="translate-tab">
          <div class="translate-tab-item" @click="selectTab(0)"
            :class="{ 'translate-tab-item-active': translateTab === 0 }">
            <img
              :src="getImgUrl(`static/image/documentUpload/origin${translateTab === 0 ? '-actived' : ''}-tab.png`)" />
            <div>原文</div>
          </div>
          <div class="translate-tab-item" @click="selectTab(1)"
            :class="{ 'translate-tab-item-active': translateTab === 1 }">
            <img
              :src="getImgUrl(`static/image/documentUpload/translate${translateTab === 1 ? '-actived' : ''}-tab.png`)" />
            <div>译文</div>
          </div>
          <div class="translate-tab-item" @click="selectTab(2)"
            :class="{ 'translate-tab-item-active': translateTab === 2 }">
            <img
              :src="getImgUrl(`static/image/documentUpload/bilingual${translateTab === 2 ? '-actived' : ''}-tab.png`)" />
            <div>双语对照</div>
          </div>
        </div>
      </div>
    </template>
    <template v-if="pdfLoading">
      <div class="loadingbox">
        <a-spin size="large" tip="加载中..." />
      </div>
    </template>
    <template v-if="loading === false && pdfState.padSource && pdfState.numPages">
      <div v-show="translateTab === 0" class="pdfContainer">
        <div v-for="i in pdfState.numPages" :key="i" ref="pdfViewer" class="pdf-box">
          <VuePdfEmbed :id="`pdf${i}`" class="pdf-embed" :page="i" text-layer :source="pdfState.padSource"
            :scale="pdfScale" :is-range-enabled="true" @rendered="handleRendered(i)" />
        </div>
      </div>

      <div class="pdfContainer parseContainer" :class="{ 'show-translate': translateTab === 1 }">
        <template v-if="isTransLateing === 1">
          <div class="loadingbox">
            <a-spin size="large" tip="加载中..." />
          </div>
        </template>
        <template v-else>
          <div v-for="(i, index) in mrkdoc" :key="index" ref="transLateViewer" class="transLate mb40">
            <div v-if="defer(index / 10)" :id="`tra${index + 1}`" v-html="i.pureUrl"></div>
          </div>
        </template>
      </div>
      <div :class="{ 'show-translate': translateTab === 2 }" class="pdfContainer parseContainer">
        <template v-if="isTransLateing === 1">
          <div class="loadingbox">
            <a-spin size="large" tip="加载中..." />
          </div>

        </template>
        <template v-else>
          <div v-for="(i, index) in mrkdoc" :key="index" ref="bilingualViewer" class="bilingual mb40">
            <div v-if="defer(index / 10)" :id="`bil${index + 1}`" v-html="i.transUrl"></div>
          </div>
        </template>

      </div>
    </template>

    <div class="bottom-operate-area">
      <div class="file-name ellipsis" style="width: 200px;">{{ props.pdfUrl.name }}</div>
      <div class="pagination-box">
        <a-button type="text" class="previous" :disabled="currentState.pageNum === 1" @click="pagePerview('previous')">
          &lt;
        </a-button>
        <div class="pagination">
          <a-input-number v-model:value="currentState.pageNum" class="pagination-input" :controls="false" :min="1"
            :max="currentState.numPages" @change="pageChangeDebounce" />/<div class="total">{{ currentState.numPages }}
          </div>
        </div>
        <a-button type="text" class="next" :disabled="currentState.pageNum === currentState.numPages"
          @click="pagePerview('next')">></a-button>
      </div>
      <div class="scale-box" v-if="translateTab === 0">
        <a-button type="text" @click="scaleControl('minus')">-</a-button>
        <a-select v-model:value="scalePercentage">
          <a-select-option v-for="item in ['50%', '80%', '100%', '200%']" :key="item" :value="item">
          </a-select-option>
        </a-select>
        <a-button type="text" @click="scaleControl('plus')">+</a-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onBeforeMount, onMounted, nextTick, defineExpose, onBeforeUnmount } from 'vue'
import VuePdfEmbed, { useVuePdfEmbed } from 'vue-pdf-embed'
import { debounce, } from 'lodash'
import lottie, { type AnimationItem } from 'lottie-web'
import { getImgUrl } from '@/utils/index'
import type { PdfFile } from '@/api/type';
import { apiTransLateAll, apiSetTranStatus } from '@/api/ai';
import { getMarkeDom } from '@/utils/index'
import { useChatBus } from '@/hook/useChatBus'
import { LANGUAGE_CODE } from '@/const'
import { cancelRequest } from '@/utils/requestUpload'
import { useDefer } from '@/hook/useDefer'
import { chunkArray, getBlob,imgTagRegex } from '@/utils'
import 'vue-pdf-embed/dist/style/textLayer.css'
import 'vue-pdf-embed/dist/style/index.css'
interface State {
  padSource?: string,
  pageNum: number,
  numPages: number,
  scale: string,
  name: string,
  size: string,
  key: string
}
interface MarkDomList {
  index: number,
  pureUrl: string,
  transUrl: string,
}

const defer = useDefer()

const props = defineProps({
  pdfUrl: {
    type: Object as () => PdfFile,
    required: true
  },
  parghList: {
    type: Array as () => string[],
    required: true
  },
  languageCode: {
    type: String as () => LANGUAGE_CODE,
    required: true
  },
  tranStatus: {
    type: Number as () => -1 | 0 | 1,
    required: true
  },
  processStatus: {
    type: Number,
    default: 3
  }
})
let numPages = 0
// const pdfScale = ref(0.5)
const pdfState = ref<State>({
  key: 'pdf',
  padSource: '',
  pageNum: 1,
  numPages: numPages,
  scale: '100%',
  name: props.pdfUrl.name,
  size: props.pdfUrl.size as string
})
const transLateState = ref<State>({
  key: 'tra',
  pageNum: 1,
  numPages: numPages,
  scale: '100%',
  name: props.pdfUrl.name,
  size: props.pdfUrl.size as string
})
const billngualState = ref<State>({
  key: 'bil',
  pageNum: 1,
  numPages: numPages,
  scale: '100%',
  name: props.pdfUrl.name,
  size: props.pdfUrl.size as string
})
const pageChangeSatus = ref<boolean>(false)
const pdfViewer = ref<HTMLElement[] | []>()
const transLateViewer = ref<HTMLElement[] | []>()
const bilingualViewer = ref<HTMLElement[] | []>()
const scalePercentage = ref<string>('100%')
const loading = ref<boolean>(false)
const isTransLateing = ref<number>(0) // 0:未翻译，1：翻译中，2：翻译完成
const translateTab = ref<number>()  // 0:原文 1：译文 2：双语对照
const translating = ref()
const animation = ref<AnimationItem>()
const mrkdoc = ref<MarkDomList[]>([])
const emit = defineEmits(['changeTranStatus'])
onMounted(async () => {
  console.log('pdfUrl', props.pdfUrl);
  const { doc: pdfDoc } = useVuePdfEmbed({ source: props.pdfUrl.url, })
  console.log('pdfDoc', pdfDoc);
  pdfState.value.padSource = pdfDoc
  const data = await getBlob(props.pdfUrl.url)
  const reader = new FileReader();
  reader.readAsArrayBuffer(data as Blob);
  reader.onloadend = async () => {
    const arrayBuffer = reader.result;
    var loadingTask = window.pdfjsLib.getDocument(arrayBuffer);
    loadingTask.promise.then(function (pdf) {
      pdfState.value.numPages = pdf.numPages
      transLateState.value.numPages = pdf.numPages
      billngualState.value.numPages = pdf.numPages
      setTimeout(() => {
        translateTab.value = 0
      }, 300)

      console.log('pdf', pdfViewer.value);
    });
  }
  initLottie()

  console.log('pdfState', translateTab.value)
})
useChatBus((e, val) => {
  switch (e) {
    case 'pageIndexClick':
      console.log('pageIndexClick', val)
      // translateTab.value = 0
      // 设置对应 xxState.value.pageNum
      pdfState.value.pageNum = Number(val)
      transLateState.value.pageNum = Number(val)
      billngualState.value.pageNum = Number(val)
      break
    default:
      ''
  }
})
watch(() => translateTab.value, () => {
  switch (translateTab.value) {
    case 0:
      console.log('pdfState', pdfViewer.value)
      if (pdfViewer.value) {
        initObserve(pdfViewer.value)
      }
      break;
    case 1:
      if (transLateViewer.value) {
        initObserve(transLateViewer.value)
      }
      break;
    case 2:
      if (bilingualViewer.value) {
        initObserve(bilingualViewer.value)
      }
      break;
    default:
      if (pdfViewer.value) {
        initObserve(pdfViewer.value)
      }
      break;
  }
}, { immediate: true })
const currentState = computed(() => {
  switch (translateTab.value) {
    case 0:
      // if (pdfViewer.value) {
      //   initObserve(pdfViewer.value)
      // }
      return pdfState.value
    case 1:
      // if (transLateViewer.value) {
      //   initObserve(transLateViewer.value)
      // }
      return transLateState.value
    default:
      // if (bilingualViewer.value) {
      //   initObserve(bilingualViewer.value)
      // }
      return billngualState.value
  }
})

watch(() => currentState.value.pageNum, async () => {
  // console.warn('watch123456',currentState.value.pageNum, pageChangeSatus.value);
  if (pageChangeSatus.value) return
  pageScrollFormPagiton()
})

const pdfScale = computed(() => dealPercentageToNum(scalePercentage.value))
// 将父盒子右移、下移
const boxScale = computed(() => `transform: scale(${dealPercentageToNum(scalePercentage.value)}) translate(calc(${scalePercentage.value} - 100%),calc(${scalePercentage.value} - 100%))`)

const pageChange = async (pageNum: number) => {
  // console.log('pageNum', pageNum, currentState)
  currentState.value.pageNum = pageNum
  pageScrollFormPagiton()
}
const pageChangeDebounce = debounce(pageChange, 300)
const pagePerview = (type: string) => {
  // console.warn(type,'type123456');

  switch (translateTab.value) {
    case 0:
      pdfState.value.pageNum = pdfState.value.pageNum + (type === 'next' ? 1 : -1)
      // pageScrollFormPagiton()
      return
    case 1:
      transLateState.value.pageNum = transLateState.value.pageNum + (type === 'next' ? 1 : -1)
      // pageScrollFormPagiton()
      return
    case 2:
      billngualState.value.pageNum = billngualState.value.pageNum + (type === 'next' ? 1 : -1)
      // pageScrollFormPagiton()
      return

  }

}
const pageScrollToView = async () => {
  if (pageChangeSatus.value) return
  pageChangeSatus.value = true
  console.log('pageScrollFormPagiton', currentState.value.pageNum, currentState.value.key + currentState.value.pageNum, document?.getElementById(currentState.value.key + currentState.value.pageNum))
  await document?.getElementById(currentState.value.key + currentState.value.pageNum)?.scrollIntoView({
    behavior: "smooth", //smooth:平滑，auto：直接定位
    block: "start",
    inline: "center",
  });
  setTimeout(() => {
    pageChangeSatus.value = false
  }, 500)
}
const pageScrollFormPagiton = debounce(pageScrollToView, 300)
const scaleControl = async (type: string) => {
  let computedValue = dealPercentageToNum(scalePercentage.value)
  if (type === 'plus' && computedValue < 2) {
    computedValue += 0.1
  } else if (type === 'minus' && pdfScale.value > 0.5) {
    computedValue -= 0.1
  }
  console.log('computedValue', computedValue)
  scalePercentage.value = dealNumToPercantage(Number(computedValue.toFixed(1)))
  pageScrollFormPagiton()
}
const dealPercentageToNum = (value: string): number => {
  console.log('value', value)
  let decimal = parseFloat(value.slice(0, -1)) / 100
  return decimal
}
const dealNumToPercantage = (value: number): string => {
  let decimal = (value * 100).toFixed(0) + '%'
  return decimal
}
const initLottie = () => {
  const container = translating.value
  // console.log('container', container)
  animation.value = lottie.loadAnimation({
    container: container,
    renderer: 'svg',
    loop: true,
    autoplay: true,
    name: 'demo',
    rendererSettings: {
      'imagePreserveAspectRatio': 'meet'
    },
    animationData: { "nm": "Comp 1", "ddd": 0, "h": 100, "w": 100, "meta": { "g": "@lottiefiles/toolkit-js 0.33.2" }, "layers": [{ "ty": 4, "nm": "Shape Layer 5", "sr": 1, "st": 20, "op": 620, "ip": 20, "hd": false, "ddd": 0, "bm": 0, "hasMask": false, "ao": 0, "ks": { "a": { "a": 0, "k": [0, 0, 0] }, "s": { "a": 0, "k": [20, 20, 100] }, "sk": { "a": 0, "k": 0 }, "p": { "a": 0, "k": [50.2, 50, 0] }, "r": { "a": 1, "k": [{ "o": { "x": 0.333, "y": 0 }, "i": { "x": 0.667, "y": 1 }, "s": [0], "t": 20 }, { "s": [360], "t": 110 }] }, "sa": { "a": 0, "k": 0 }, "o": { "a": 0, "k": 100 } }, "ef": [], "shapes": [{ "ty": "gr", "bm": 0, "hd": false, "mn": "ADBE Vector Group", "nm": "Ellipse 1", "ix": 1, "cix": 2, "np": 3, "it": [{ "ty": "el", "bm": 0, "hd": false, "mn": "ADBE Vector Shape - Ellipse", "nm": "Ellipse Path 1", "d": 1, "p": { "a": 0, "k": [0, -100] }, "s": { "a": 0, "k": [10, 10] } }, { "ty": "st", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Stroke", "nm": "Stroke 1", "lc": 1, "lj": 1, "ml": 4, "o": { "a": 0, "k": 100 }, "w": { "a": 0, "k": 0 }, "c": { "a": 0, "k": [0, 0, 0] } }, { "ty": "fl", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Fill", "nm": "Fill 1", "c": { "a": 0, "k": [1, 1, 1] }, "r": 1, "o": { "a": 0, "k": 100 } }, { "ty": "tr", "a": { "a": 0, "k": [0, 0], "ix": 1 }, "s": { "a": 0, "k": [100, 100], "ix": 3 }, "sk": { "a": 0, "k": 0, "ix": 4 }, "p": { "a": 0, "k": [0, 0], "ix": 2 }, "r": { "a": 0, "k": 0, "ix": 6 }, "sa": { "a": 0, "k": 0, "ix": 5 }, "o": { "a": 0, "k": 100, "ix": 7 } }] }], "ind": 1 }, { "ty": 4, "nm": "Shape Layer 4", "sr": 1, "st": 15, "op": 615, "ip": 15, "hd": false, "ddd": 0, "bm": 0, "hasMask": false, "ao": 0, "ks": { "a": { "a": 0, "k": [0, 0, 0] }, "s": { "a": 0, "k": [20, 20, 100] }, "sk": { "a": 0, "k": 0 }, "p": { "a": 0, "k": [50.2, 50, 0] }, "r": { "a": 1, "k": [{ "o": { "x": 0.333, "y": 0 }, "i": { "x": 0.667, "y": 1 }, "s": [0], "t": 15 }, { "s": [360], "t": 105 }] }, "sa": { "a": 0, "k": 0 }, "o": { "a": 0, "k": 100 } }, "ef": [], "shapes": [{ "ty": "gr", "bm": 0, "hd": false, "mn": "ADBE Vector Group", "nm": "Ellipse 1", "ix": 1, "cix": 2, "np": 3, "it": [{ "ty": "el", "bm": 0, "hd": false, "mn": "ADBE Vector Shape - Ellipse", "nm": "Ellipse Path 1", "d": 1, "p": { "a": 0, "k": [0, -100] }, "s": { "a": 0, "k": [20, 20] } }, { "ty": "st", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Stroke", "nm": "Stroke 1", "lc": 1, "lj": 1, "ml": 4, "o": { "a": 0, "k": 100 }, "w": { "a": 0, "k": 0 }, "c": { "a": 0, "k": [0, 0, 0] } }, { "ty": "fl", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Fill", "nm": "Fill 1", "c": { "a": 0, "k": [1, 1, 1] }, "r": 1, "o": { "a": 0, "k": 100 } }, { "ty": "tr", "a": { "a": 0, "k": [0, 0], "ix": 1 }, "s": { "a": 0, "k": [100, 100], "ix": 3 }, "sk": { "a": 0, "k": 0, "ix": 4 }, "p": { "a": 0, "k": [0, 0], "ix": 2 }, "r": { "a": 0, "k": 0, "ix": 6 }, "sa": { "a": 0, "k": 0, "ix": 5 }, "o": { "a": 0, "k": 100, "ix": 7 } }] }], "ind": 2 }, { "ty": 4, "nm": "Shape Layer 3", "sr": 1, "st": 10, "op": 610, "ip": 10, "hd": false, "ddd": 0, "bm": 0, "hasMask": false, "ao": 0, "ks": { "a": { "a": 0, "k": [0, 0, 0] }, "s": { "a": 0, "k": [20, 20, 100] }, "sk": { "a": 0, "k": 0 }, "p": { "a": 0, "k": [50.2, 50, 0] }, "r": { "a": 1, "k": [{ "o": { "x": 0.333, "y": 0 }, "i": { "x": 0.667, "y": 1 }, "s": [0], "t": 10 }, { "s": [360], "t": 100 }] }, "sa": { "a": 0, "k": 0 }, "o": { "a": 0, "k": 100 } }, "ef": [], "shapes": [{ "ty": "gr", "bm": 0, "hd": false, "mn": "ADBE Vector Group", "nm": "Ellipse 1", "ix": 1, "cix": 2, "np": 3, "it": [{ "ty": "el", "bm": 0, "hd": false, "mn": "ADBE Vector Shape - Ellipse", "nm": "Ellipse Path 1", "d": 1, "p": { "a": 0, "k": [0, -100] }, "s": { "a": 0, "k": [30, 30] } }, { "ty": "st", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Stroke", "nm": "Stroke 1", "lc": 1, "lj": 1, "ml": 4, "o": { "a": 0, "k": 100 }, "w": { "a": 0, "k": 0 }, "c": { "a": 0, "k": [0, 0, 0] } }, { "ty": "fl", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Fill", "nm": "Fill 1", "c": { "a": 0, "k": [1, 1, 1] }, "r": 1, "o": { "a": 0, "k": 100 } }, { "ty": "tr", "a": { "a": 0, "k": [0, 0], "ix": 1 }, "s": { "a": 0, "k": [100, 100], "ix": 3 }, "sk": { "a": 0, "k": 0, "ix": 4 }, "p": { "a": 0, "k": [0, 0], "ix": 2 }, "r": { "a": 0, "k": 0, "ix": 6 }, "sa": { "a": 0, "k": 0, "ix": 5 }, "o": { "a": 0, "k": 100, "ix": 7 } }] }], "ind": 3 }, { "ty": 4, "nm": "Shape Layer 2", "sr": 1, "st": 5, "op": 605, "ip": 5, "hd": false, "ddd": 0, "bm": 0, "hasMask": false, "ao": 0, "ks": { "a": { "a": 0, "k": [0, 0, 0] }, "s": { "a": 0, "k": [20, 20, 100] }, "sk": { "a": 0, "k": 0 }, "p": { "a": 0, "k": [50.2, 50, 0] }, "r": { "a": 1, "k": [{ "o": { "x": 0.333, "y": 0 }, "i": { "x": 0.667, "y": 1 }, "s": [0], "t": 5 }, { "s": [360], "t": 95 }] }, "sa": { "a": 0, "k": 0 }, "o": { "a": 0, "k": 100 } }, "ef": [], "shapes": [{ "ty": "gr", "bm": 0, "hd": false, "mn": "ADBE Vector Group", "nm": "Ellipse 1", "ix": 1, "cix": 2, "np": 3, "it": [{ "ty": "el", "bm": 0, "hd": false, "mn": "ADBE Vector Shape - Ellipse", "nm": "Ellipse Path 1", "d": 1, "p": { "a": 0, "k": [0, -100] }, "s": { "a": 0, "k": [40, 40] } }, { "ty": "st", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Stroke", "nm": "Stroke 1", "lc": 1, "lj": 1, "ml": 4, "o": { "a": 0, "k": 100 }, "w": { "a": 0, "k": 0 }, "c": { "a": 0, "k": [0, 0, 0] } }, { "ty": "fl", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Fill", "nm": "Fill 1", "c": { "a": 0, "k": [1, 1, 1] }, "r": 1, "o": { "a": 0, "k": 100 } }, { "ty": "tr", "a": { "a": 0, "k": [0, 0], "ix": 1 }, "s": { "a": 0, "k": [100, 100], "ix": 3 }, "sk": { "a": 0, "k": 0, "ix": 4 }, "p": { "a": 0, "k": [0, 0], "ix": 2 }, "r": { "a": 0, "k": 0, "ix": 6 }, "sa": { "a": 0, "k": 0, "ix": 5 }, "o": { "a": 0, "k": 100, "ix": 7 } }] }], "ind": 4 }, { "ty": 4, "nm": "Shape Layer 1", "sr": 1, "st": 0, "op": 600, "ip": 0, "hd": false, "ddd": 0, "bm": 0, "hasMask": false, "ao": 0, "ks": { "a": { "a": 0, "k": [0, 0, 0] }, "s": { "a": 0, "k": [20, 20, 100] }, "sk": { "a": 0, "k": 0 }, "p": { "a": 0, "k": [50, 50, 0] }, "r": { "a": 1, "k": [{ "o": { "x": 0.333, "y": 0 }, "i": { "x": 0.667, "y": 1 }, "s": [0], "t": 0 }, { "s": [360], "t": 90 }] }, "sa": { "a": 0, "k": 0 }, "o": { "a": 0, "k": 100 } }, "ef": [], "shapes": [{ "ty": "gr", "bm": 0, "hd": false, "mn": "ADBE Vector Group", "nm": "Ellipse 1", "ix": 1, "cix": 2, "np": 3, "it": [{ "ty": "el", "bm": 0, "hd": false, "mn": "ADBE Vector Shape - Ellipse", "nm": "Ellipse Path 1", "d": 1, "p": { "a": 0, "k": [0, -100] }, "s": { "a": 1, "k": [{ "o": { "x": 0.333, "y": 0 }, "i": { "x": 0.667, "y": 1 }, "s": [50, 50], "t": 0 }, { "o": { "x": 0.333, "y": 0 }, "i": { "x": 0.667, "y": 1 }, "s": [40, 40], "t": 84 }, { "s": [50, 50], "t": 100 }] } }, { "ty": "st", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Stroke", "nm": "Stroke 1", "lc": 1, "lj": 1, "ml": 4, "o": { "a": 0, "k": 100 }, "w": { "a": 0, "k": 0 }, "c": { "a": 0, "k": [0, 0, 0] } }, { "ty": "fl", "bm": 0, "hd": false, "mn": "ADBE Vector Graphic - Fill", "nm": "Fill 1", "c": { "a": 0, "k": [1, 1, 1] }, "r": 1, "o": { "a": 0, "k": 100 } }, { "ty": "tr", "a": { "a": 0, "k": [0, 0], "ix": 1 }, "s": { "a": 0, "k": [100, 100], "ix": 3 }, "sk": { "a": 0, "k": 0, "ix": 4 }, "p": { "a": 0, "k": [0, 0], "ix": 2 }, "r": { "a": 0, "k": 0, "ix": 6 }, "sa": { "a": 0, "k": 0, "ix": 5 }, "o": { "a": 0, "k": 100, "ix": 7 } }] }], "ind": 5 }], "v": "4.6.8", "fr": 60, "op": 106, "ip": 0, "assets": [] }
  })
}

const getMarkContent = (urlArr: string[], key: any, baseIndex: any, isLastGroup: boolean = false) => {
  return new Promise(async (resolve) => {
    await Promise.all(urlArr.map(url => getMarkeDom(url))).then((res) => {
      res.forEach((resContent, index) => {
        if (!mrkdoc.value[baseIndex + index]) {
          mrkdoc.value[baseIndex + index] = {
            index: baseIndex + index + 1,
            pureUrl: '',
            transUrl: ''
          }
        }
        mrkdoc.value[baseIndex + index][key] = imgTagRegex(resContent as string)  
        if (isLastGroup && index === res.length - 1) {
          apiSetTranStatus({ paperid: props.pdfUrl.paperId, trans_status: 1 })
          emit('changeTranStatus', 1)
          animation.value?.stop?.()
        }
        // console.warn('加载完毕',baseIndex + index);

      })
    })
    resolve(true)
  })
}
//  const imgTagRegex =  (richText: string) =>{
// 	const imgTagRegex = /https?:\/\/[^\s/$.?#].[^\s]*\.(png|jpg)/g

//   richText = richText.replace(imgTagRegex, (match: any, href:any, text:any) => {
//     console.log('imgTagRegex', match, href, text)
// 		  return `<img style="width: 100%;" src="${match}" alt="${text}" />`;
// 	});
//   return  richText
// }

// -1 未翻译 0 翻译中 1 翻译完成
const startTranslate = async (type: number) => {
  isTransLateing.value = 1
  initLottie()
  nextTick(() => {
    animation.value?.play()
  })
  if (type === 0) {
    apiSetTranStatus({ paperid: props.pdfUrl.paperId, trans_status: 0 })
    emit('changeTranStatus', 0)
  }
  console.log(312312, props.pdfUrl)
  const { data: { data } } = await apiTransLateAll({ paperid: props.pdfUrl.paperId })
  if (data.length) {
    let pureUrls: any[] = []
    let transUrls: any[] = []
    data.forEach((c: string[]) => {
      pureUrls.push(c[0])
      transUrls.push(c[1])
    })
    pureUrls = chunkArray(pureUrls, 10)
    transUrls = chunkArray(transUrls, 10)

    await getMarkContent(pureUrls.shift(), 'pureUrl', 0, pureUrls.length === 0)
    await getMarkContent(transUrls.shift(), 'transUrl', 0, transUrls.length === 0)
    pdfLoading.value = false
    isTransLateing.value = 2
    // console.error('加载完毕11');
    if (pureUrls?.length) {
      pureUrls.forEach(async (p, pIndex) => {
        getMarkContent(p, 'pureUrl', (pIndex + 1) * 10, pIndex === pureUrls.length - 1)
      })
      transUrls.forEach(async (t, tIndex) => {
        getMarkContent(t, 'transUrl', (tIndex + 1) * 10, tIndex === transUrls.length - 1)
      })
    }
  }

}

const selectTab = (index: number) => {
  translateTab.value = index
  pageChangeSatus.value = true
  document.querySelector('.parseContainer').scrollLeft = 0
  setTimeout(() => {
    pageChangeSatus.value = false
  }, 1000)

}

const initObserve = (value: HTMLElement[]) => {
  console.log('initObserve')
  setTimeout(() => {
    const container = document.querySelector('.pdfContainer')
    value.forEach(item => {
      const observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            const target = entry.target
            console.log('target', target, target.offsetTop, 'target,target.clientHeight:', target, target.clientHeight)
            if (target && (!pageChangeSatus.value || target.offsetTop === 80 || (target.clientHeight + target.offsetTop === container?.scrollHeight))) {
              const id = target.querySelector('*')?.id
              const pageNum = id && Number(id.slice(3)) || 1
              console.log('pageNum', pageNum, id && Number(id.slice(3)) || 1)
              translateTab.value === 0 ? pdfState.value.pageNum = pageNum : translateTab.value == 1 ? transLateState.value.pageNum = pageNum : billngualState.value.pageNum = pageNum
              pdfState.value.pageNum = id && Number(id.slice(3)) || 1
              pageChangeSatus.value = true
              setTimeout(() => {
                pageChangeSatus.value = false
              }, 300)
            }
            // 当元素进入视口时的处理逻辑
          }
        });
      });
      observer.observe(item)
    })
  }, 400)
}

const pdfLoading = ref(false)
const handleRendered = (i) => {
  if (!pdfLoading.value) return
  pdfLoading.value = false

}

defineExpose({ startTranslate })

onBeforeUnmount(() => {
  cancelRequest()
})
</script>
<style lang="scss" scoped>
.pdf-viewer {
  height: calc(100% - 18px);
  background: #fff;
  position: relative;

  // margin-top: 6px;
  .pdf-box {
    ::selection {
      color: transparent !important;
    }
  }

  .parseContainer {
    ::selection {
      color: inherit;
        background-color: #BBD6FB;
      }
  }

  .top-operate-area {
    display: flex;
    justify-content: center;
    padding: 24px 0;
    background: #fff;
    position: absolute;
    top: 0;
    // width: 100%;
    width: calc(100% - 6px);
    z-index: 30;

    .sigle-translate {
      background: #2A8BF2;
      color: #FFF;
      border-radius: 6px;
      line-height: 20px;
      display: flex;
      height: 32px;
      align-items: center;
      overflow: hidden;
      padding: 12px;

      .translating {
        width: 38px;
        height: 38px;
      }

      img {
        width: 20px;
        height: 20px;
        margin-right: 4px;
      }
    }

    .translate-tab {
      display: flex;
      justify-content: space-between;
      border-radius: 6px;
      border: 1px dashed #5C5E61;
      align-items: center;

      .translate-tab-item {
        width: 104px;
        color: #5C5E61;
        font-size: 14px;
        border-radius: 6px;
        display: flex;
        padding: 6px 0;
        background: #fff;
        justify-content: center;
        align-items: center;

        img {
          width: 20px;
          height: 20px;
          margin-right: 4px;
        }
      }

      .translate-tab-item-active {
        background: #2A8BF2;
        color: #fff;
      }
    }

    // .translate-tab :nth-child(2){
    //     margin: 0 16px;
    // }
  }

  .transLate {
    width: 100%;
    word-break: break-all;
    // word-wrap: break-word;
    // overflow: scroll;
    // content-visibility: auto;
  }

  .bilingual {
    width: 100%;
    word-break: break-all;
  }

  .pdfContainer {
    height: calc(100% - 50px);
    overflow-y: scroll;
    width: 100%;
    padding-top: 80px;
    // margin-top: 480px;
    display: flex;
    flex-direction: column;

    &::-webkit-scrollbar {
      height: 8px;
      width: 8px;
    }

    &::-webkit-scrollbar {
      height: 8px;
      width: 8px;
    }

    .pdf-box {
      // height: max-content;
      flex: 1;


      // height: 500px;
      .pdf-embed {
        width: 100%;
        height: 100%;

        :deep() canvas {
          width: auto !important;
          height: auto !important;
        }
      }
    }


  }

  .loadingbox {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    text-align: center;
    justify-content: center;
  }

  .parseContainer {
    padding: 0;
    // word-break: break-all;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow-x: scroll;
    visibility: hidden;
    height: 0;
    box-sizing: border-box;

    // .bilingual {
    //   margin-bottom: 40px;
    // }
    &.show-translate {
      padding: 84px 55px 0;
      visibility: visible;
      height: 100%;
    }

  }

  .bottom-operate-area {
    position: sticky;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 50px;
    background: #fff;
    border-top: 1px solid #ccc;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;

    .file-name {
      font-size: 16px;
      color: #0D1C2E;
    }

    .pagination-box {
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      line-height: 30px;

      .pagination {
        display: flex;
        align-items: center;

        .total {
          color: #292929;
          margin-left: 6px;
        }

        .pagination-input {
          width: 44px;
          margin-right: 6px;
        }
      }
    }

    .scale-box {
      display: flex;
    }
  }
}

merror {
  display: none;
}
</style>
<style>
.MJX-TEX {
  /* width: 100%; */
  white-space: pre-wrap;

}

merror {
  display: none;
}

.MJX-TEX:has(merror) {
  display: none;
}

mjx-merror {
  display: none;
}

.justify-content-center {
  justify-content: center;
}

.textLayer ::selection {
  background: #006CFF
}
</style>